package cn.ad.server.web.spring.service.components.adtraffic2;

import cn.ad.server.web.spring.model.jesgoo.JesgooAdFormat;
import cn.ad.server.web.spring.model.jesgoo.JesgooConnection;
import cn.ad.server.web.spring.model.jesgoo.JesgooOperator;
import cn.ad.server.web.spring.model.jesgoo.request.*;
import cn.ad.server.web.spring.model.jesgoo.response.SellerResponse;
import cn.ad.server.web.spring.model.sts.STSAdResponse;
import cn.ad.server.web.spring.service.actions.context.AdContext;
import cn.ad.server.web.spring.service.actions.handler.gdt.server.HttpConnectionManager;
import cn.ad.server.web.utils.JsonUtils;
import cn.ad.server.domain.ad.AdSpaceAdxMap;
import cn.ad.server.domain.ad.AdTemplate;
import cn.ad.server.domain.enumration.ActionType;
import cn.ad.server.domain.enumration.AdFormat;
import cn.ad.server.domain.enumration.Connection;
import cn.ad.server.domain.enumration.OS;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zooy on 17-1-23.
 */
@Component
public class JesgooSSPDispatcher implements SSPDispatcher{

    private static Logger logger = LoggerFactory.getLogger(JesgooSSPDispatcher.class);

    private final String requestAddress = "http://api.jesgoo.com/v1/json";

    @Resource
    private String serverAddress;

    @Autowired
    private HttpConnectionManager httpConnectionManager;

    @Override
    public STSAdResponse.AdSpace request(AdContext adContext, STSAdResponse.AdSpace adSpace, AdTemplate adTemplate, AdSpaceAdxMap adSpaceAdxMap) {

        //设置转发失败
        adContext.setForwardType(2);
        String json = compositeParam(adContext, adSpaceAdxMap);

        CloseableHttpClient httpClient = httpConnectionManager.getHttpClient();
        HttpPost httpPost = new HttpPost(requestAddress);
        InputStream ins = null;
        try {
            StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解决中文乱码问题
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

            ins = httpResponse.getEntity().getContent();

            if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {

                //拼接返回参数
                SellerResponse response = JsonUtils.toObject(ins, SellerResponse.class);
                if (response.isSuccess() && response.getAds() != null) {

                    STSAdResponse.Creative creative = new STSAdResponse.Creative();
                    //设置展示地址
                    creative.setImpression(new String[]{compositeLocalImpUrl(adContext)});
                    STSAdResponse.Event event = new STSAdResponse.Event();
                    event.setEventKey(ActionType.LINK_JUMP.getValue());
                    creative.setHtmlSnippet(response.getAds()[0].getHtml_snippet());
                    creative.setIs_html(true);
                    creative.setEvent(new STSAdResponse.Event[]{event});
                    //设置点击地址
                    creative.setClick(new String[]{compositeLocalClickUrl(adContext)});
                    adSpace.setCreative(new STSAdResponse.Creative[]{creative});
                    adContext.setForwardType(1);
                    return adSpace;
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public String compositeParam(AdContext adContext, AdSpaceAdxMap adSpaceAdxMap) {

        SellerRequest sellerRequest = new SellerRequest();
        /**
         * media
         */
        Media media = new Media();
        //设置媒体类别为app
        media.setType(1);

        //设置app信息
        App app = new App();
        app.setPackage_name(adSpaceAdxMap.getPackageName());
        media.setApp(app);

        //设置site信息，暂时没有信息对应

        //设置browser信息
        Browser browser = new Browser();
        browser.setUser_agent(adContext.getUa());
        media.setBrowser(browser);
        sellerRequest.setMedia(media);

        /**
         * device
         */
        //设置device
        Device device = new Device();
        //默认设置为手机
        device.setType(2);

        //设置Ids
        List<Id> ids = new ArrayList<>();
        if (OS.osMap.get(adContext.getOs()) == OS.IOS) {
            Id id = new Id();
            if (!StringUtils.isEmpty(adContext.getIdfaori())) {
                id.setType(3);
                id.setId(adContext.getIdfaori());
            } else {
                id.setType(3);
                id.setId(adContext.getIdfa());
                id.setMd5(true);
            }
            ids.add(id);
        } else if((OS.osMap.get(adContext.getOs()) == OS.ANDROID)) {
            if (!StringUtils.isEmpty(adContext.getImeiori())) {
                Id id = new Id();
                id.setType(1);
                id.setId(adContext.getImeiori());
                ids.add(id);
            } else if (!StringUtils.isEmpty(adContext.getImei())) {
                Id id = new Id();
                id.setType(1);
                id.setId(adContext.getImei());
                id.setMd5(true);
                ids.add(id);
            }

            if (!StringUtils.isEmpty(adContext.getMac())) {
                Id id = new Id();
                id.setType(2);
                id.setId(adContext.getMac());
                id.setMd5(true);
                ids.add(id);
            }

            if (!StringUtils.isEmpty(adContext.getAndroidId())) {
                Id id = new Id();
                id.setType(6);
                id.setId(adContext.getAndroidId());
                id.setMd5(true);
                ids.add(id);
            }
        }

        device.setIds(ids);
        //设置操作系统类型
        device.setOs_type(adContext.getOs());
        //设置设备版本号
        Version os_version = new Version();
        String osVersion = adContext.getOsVersion();
        if (!StringUtils.isEmpty(osVersion)) {
            String[] split = osVersion.split("\\.");
            os_version.setMajor(Integer.parseInt(split[0]));
            os_version.setMinor(Integer.parseInt(split[1]));
        }
        device.setOs_version(os_version);
        device.setBrand(adContext.getBrand());
        device.setModel(adContext.getModel());
        //设置屏幕尺寸
        Size screenSize = new Size();
        screenSize.setWidth(adContext.getScreenWidth());
        screenSize.setHeight(adContext.getScreenHeight());
        device.setScreen_size(screenSize);
        //设置屏幕像素密度 -- 没有对应
        sellerRequest.setDevice(device);

        /**
         * network
         */
        //设置设备的网络环境
        Network network = new Network();
        network.setIp(adContext.getIp());
        //设备的联网类型
        network.setType(JesgooConnection.jesgooConnectionMap.get(Connection.connectionMap.get(adContext.getConnType())));
        network.setCellular_operator(JesgooOperator.jesgooOperatorMap.get(adContext.getMob_ops()));
        sellerRequest.setNetwork(network);

        /**
         * client
         */
        //设置广告客户端类型
        Client client = new Client();
        client.setType(3);
        Version clientVersion = new Version();
        clientVersion.setMajor(1);
        clientVersion.setMinor(3);
        client.setVersion(clientVersion);
        sellerRequest.setClient(client);

        /**
         * geo
         */
        //设置地理对象
        Geo geo = new Geo();
        geo.setType(1);
        geo.setLongitude(adContext.getLongitude());
        geo.setLatitude(adContext.getLatitude());
        geo.setTimestamp(adContext.getRequestTimestamp());
        sellerRequest.setGeo(geo);

        /**
         * adslots
         */
        AdSlot adSlot = new AdSlot();
        adSlot.setId(adSpaceAdxMap.getAdxSpaceId());
        adSlot.setType(JesgooAdFormat.FORMAT_MAP.get(AdFormat.adFormatMap.get(adSpaceAdxMap.getRequestAdFormat())));
        adSlot.setCapacity(1);
        Size slotSize = new Size();
        if (adSpaceAdxMap.getWidth() > 0) {
            slotSize.setWidth(adSpaceAdxMap.getWidth());
            slotSize.setHeight(adSpaceAdxMap.getHeight());
        } else {
            slotSize.setWidth(adContext.getAdSpaceWidth());
            slotSize.setHeight(adContext.getAdSpaceHeight());
        }
        adSlot.setSize(slotSize);
        sellerRequest.setAdslots(new AdSlot[]{adSlot});
        sellerRequest.setDebug(true);

        return JsonUtils.toJson(sellerRequest);
    }

    private String compositeLocalClickUrl(AdContext adContext) {
        String impUrlFormat = serverAddress + "v2/forward/click/ch/9?version=%s&aid=%s&sid=%s";
        return String.format(impUrlFormat, adContext.getVersion(), adContext.getAdSpaceId(), 0);
    }

    private String compositeLocalImpUrl(AdContext adContext) {
        String impUrlFormat = serverAddress + "v2/forward/imp/ch/9?version=%s&aid=%s&sid=%s";
        return String.format(impUrlFormat, adContext.getVersion(), adContext.getAdSpaceId(), 0);
    }

}
